import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'detail_state.dart';
import '../../data/models/prompt_model.dart';
import '../../data/services/storage_service.dart';

/// 详情页面逻辑控制器 - Detail Page Logic Controller
/// 处理详情页面的业务逻辑，包括数据加载、操作处理、状态管理等
class DetailLogic extends GetxController {
  final DetailState state = DetailState();

  @override
  void onInit() {
    super.onInit();
    _initializeData();
  }

  @override
  void onClose() {
    state.dispose();
    super.onClose();
  }

  /// 初始化数据 - Initialize Data
  void _initializeData() {
    final promptId = Get.parameters['id'];
    if (promptId != null && promptId.isNotEmpty) {
      loadPromptDetail(promptId);
    } else {
      Get.snackbar(
        '错误',
        '无效的 Prompt ID',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
      Get.back();
    }
  }

  /// 加载 Prompt 详情 - Load Prompt Detail
  Future<void> loadPromptDetail(String promptId) async {
    try {
      state.isLoading.value = true;
      state.error.value = '';

      // 从存储服务加载 Prompt - Load Prompt from Storage Service
      final prompt = await StorageService.to.loadPrompt(promptId);
      
      if (prompt != null) {
        state.prompt.value = prompt;
        
        // 加载版本历史 - Load Version History
        await _loadVersionHistory(promptId);
        
        // 增加使用次数 - Increment Usage Count
        await _incrementUsageCount(prompt);
        
        // print('Prompt 详情加载成功 - Prompt detail loaded successfully: ${prompt.title}');
      } else {
        state.error.value = 'Prompt 不存在或已被删除';
        Get.snackbar(
          '错误',
          'Prompt 不存在或已被删除',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[800],
        );
      }
    } catch (e) {
      state.error.value = '加载失败: $e';
      // print('加载 Prompt 详情失败 - Failed to load prompt detail: $e');
      Get.snackbar(
        '错误',
        '加载失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    } finally {
      state.isLoading.value = false;
    }
  }

  /// 加载版本历史 - Load Version History
  Future<void> _loadVersionHistory(String promptId) async {
    try {
      final versionData = await StorageService.to.getVersionHistory(promptId);
      final versions = versionData.map((v) => v['version']?.toString() ?? '').toList();
      state.versions.assignAll(versions);
    } catch (e) {
      // print('加载版本历史失败 - Failed to load version history: $e');
    }
  }

  /// 增加使用次数 - Increment Usage Count
  Future<void> _incrementUsageCount(PromptModel prompt) async {
    try {
      final updatedPrompt = prompt.incrementUsage();
      await StorageService.to.savePrompt(updatedPrompt);
      state.prompt.value = updatedPrompt;
    } catch (e) {
      // print('更新使用次数失败 - Failed to update usage count: $e');
    }
  }

  /// 切换收藏状态 - Toggle Favorite Status
  Future<void> toggleFavorite() async {
    try {
      final currentPrompt = state.prompt.value;
      if (currentPrompt == null) return;

      final updatedPrompt = currentPrompt.toggleFavorite();
      await StorageService.to.savePrompt(updatedPrompt);
      state.prompt.value = updatedPrompt;

      Get.snackbar(
        updatedPrompt.getIsFavorite() ? '已收藏' : '已取消收藏',
        updatedPrompt.title,
        snackPosition: SnackPosition.TOP,
        backgroundColor: updatedPrompt.getIsFavorite() ? Colors.red[100] : Colors.grey[100],
        colorText: updatedPrompt.getIsFavorite() ? Colors.red[800] : Colors.grey[800],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      // print('切换收藏状态失败 - Failed to toggle favorite: $e');
      Get.snackbar(
        '错误',
        '操作失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 分享 Prompt - Share Prompt
  Future<void> sharePrompt() async {
    try {
      final prompt = state.prompt.value;
      if (prompt == null) return;

      // 构建分享内容 - Build Share Content
      final shareContent = '''
${prompt.title}

${prompt.description.isNotEmpty ? '${prompt.description}\n\n' : ''}${prompt.content}

---
分类: ${prompt.category}
标签: ${prompt.tags.join(', ')}
格式: ${prompt.getFormat().toUpperCase()}
版本: ${prompt.version}
''';

      // 复制到剪贴板 - Copy to Clipboard
      await Clipboard.setData(ClipboardData(text: shareContent));
      
      Get.snackbar(
        '已复制',
        'Prompt 内容已复制到剪贴板',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      // print('分享失败 - Failed to share: $e');
      Get.snackbar(
        '错误',
        '分享失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 复制内容 - Copy Content
  Future<void> copyContent() async {
    try {
      final prompt = state.prompt.value;
      if (prompt == null) return;

      await Clipboard.setData(ClipboardData(text: prompt.content));
      
      Get.snackbar(
        '已复制',
        'Prompt 内容已复制到剪贴板',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      // print('复制失败 - Failed to copy: $e');
      Get.snackbar(
        '错误',
        '复制失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 切换预览模式 - Toggle Preview Mode
  void togglePreviewMode() {
    state.isPreviewMode.value = !state.isPreviewMode.value;
  }

  /// 使用 Prompt - Use Prompt
  void usePrompt() {
    final prompt = state.prompt.value;
    if (prompt == null) return;

    if (prompt.getHasTemplateVariables()) {
      // 如果有模板变量，显示变量填写对话框 - Show Variable Input Dialog if Has Template Variables
      _showVariableInputDialog(prompt);
    } else {
      // 直接复制内容 - Copy Content Directly
      copyContent();
    }
  }

  /// 显示变量输入对话框 - Show Variable Input Dialog
  void _showVariableInputDialog(PromptModel prompt) {
    final variableControllers = <String, TextEditingController>{};
    
    // 为每个变量创建控制器 - Create Controller for Each Variable
    for (final variable in prompt.templateVariables) {
      variableControllers[variable.name] = TextEditingController(
        text: variable.defaultValue,
      );
    }

    Get.dialog(
      AlertDialog(
        title: const Text('填写模板变量'),
        content: SizedBox(
          width: double.maxFinite,
          child: SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: prompt.templateVariables.map((variable) {
                final controller = variableControllers[variable.name]!;
                
                return Padding(
                  padding: const EdgeInsets.only(bottom: 16),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Row(
                        children: [
                          Text(
                            variable.name,
                            style: const TextStyle(
                              fontWeight: FontWeight.w500,
                            ),
                          ),
                          if (variable.isRequired) ...[
                            const SizedBox(width: 4),
                            const Text(
                              '*',
                              style: TextStyle(color: Colors.red),
                            ),
                          ],
                        ],
                      ),
                      
                      if (variable.description.isNotEmpty) ...[
                        const SizedBox(height: 4),
                        Text(
                          variable.description,
                          style: TextStyle(
                            fontSize: 12,
                            color: Colors.grey[600],
                          ),
                        ),
                      ],
                      
                      const SizedBox(height: 8),
                      
                      TextField(
                        controller: controller,
                        maxLines: variable.type == 'multiline' ? 3 : 1,
                        decoration: InputDecoration(
                          hintText: variable.defaultValue.isNotEmpty 
                              ? variable.defaultValue 
                              : '请输入${variable.name}',
                          border: const OutlineInputBorder(),
                          contentPadding: const EdgeInsets.symmetric(
                            horizontal: 12,
                            vertical: 8,
                          ),
                        ),
                      ),
                    ],
                  ),
                );
              }).toList(),
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () {
              // 清理控制器 - Clean Up Controllers
              for (final controller in variableControllers.values) {
                controller.dispose();
              }
              Get.back();
            },
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () {
              _processVariableInput(prompt, variableControllers);
            },
            child: const Text('生成'),
          ),
        ],
      ),
    );
  }

  /// 处理变量输入 - Process Variable Input
  void _processVariableInput(
    PromptModel prompt,
    Map<String, TextEditingController> controllers,
  ) {
    try {
      final values = <String, String>{};
      
      // 收集变量值 - Collect Variable Values
      for (final entry in controllers.entries) {
        values[entry.key] = entry.value.text.trim();
      }
      
      // 检查必需变量 - Check Required Variables
      final missingRequired = prompt.getMissingRequiredVariables(values);
      if (missingRequired.isNotEmpty) {
        Get.snackbar(
          '错误',
          '请填写必需变量: ${missingRequired.join(', ')}',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[800],
        );
        return;
      }
      
      // 替换变量并复制 - Replace Variables and Copy
      final processedContent = prompt.replaceVariables(values);
      Clipboard.setData(ClipboardData(text: processedContent));
      
      // 清理控制器 - Clean Up Controllers
      for (final controller in controllers.values) {
        controller.dispose();
      }
      
      Get.back();
      Get.snackbar(
        '已生成',
        '处理后的 Prompt 已复制到剪贴板',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
        duration: const Duration(seconds: 3),
      );
    } catch (e) {
      // print('处理变量输入失败 - Failed to process variable input: $e');
      Get.snackbar(
        '错误',
        '处理失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 处理菜单操作 - Handle Menu Action
  void handleMenuAction(String action) {
    switch (action) {
      case 'edit':
        editPrompt();
        break;
      case 'duplicate':
        duplicatePrompt();
        break;
      case 'export':
        exportPrompt();
        break;
      case 'versions':
        viewVersionHistory();
        break;
      case 'delete':
        deletePrompt();
        break;
    }
  }

  /// 编辑 Prompt - Edit Prompt
  void editPrompt() {
    final prompt = state.prompt.value;
    if (prompt == null) return;

    Get.toNamed('/edit', parameters: {'id': prompt.id});
  }

  /// 复制 Prompt - Duplicate Prompt
  Future<void> duplicatePrompt() async {
    try {
      final prompt = state.prompt.value;
      if (prompt == null) return;

      // 创建新的 PromptModel 实例，替换 copyWith - Create new PromptModel instance instead of copyWith
      final duplicatedPrompt = PromptModel(
        id: 'prompt_${DateTime.now().millisecondsSinceEpoch}',
        title: '${prompt.title} (副本)',
        content: prompt.content,
        tags: prompt.tags,
        category: prompt.category,
        description: prompt.description,
        createdAt: DateTime.now(),
        lastModified: DateTime.now(),
        version: 1,
        filePath: prompt.filePath,
        fileFormat: prompt.fileFormat,
        metadata: prompt.metadata,
        usageCount: 0,
        templateVariables: prompt.templateVariables,
      );

      await StorageService.to.savePrompt(duplicatedPrompt);
      
      Get.snackbar(
        '已复制',
        'Prompt 已复制成功',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.green[100],
        colorText: Colors.green[800],
        duration: const Duration(seconds: 2),
      );
    } catch (e) {
      // print('复制 Prompt 失败 - Failed to duplicate prompt: $e');
      Get.snackbar(
        '错误',
        '复制失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 导出 Prompt - Export Prompt
  void exportPrompt() {
    final prompt = state.prompt.value;
    if (prompt == null) return;

    Get.dialog(
      AlertDialog(
        title: const Text('导出格式'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            ListTile(
              leading: const Icon(Icons.description),
              title: const Text('Markdown (.md)'),
              onTap: () => _performExport('md'),
            ),
            ListTile(
              leading: const Icon(Icons.text_snippet),
              title: const Text('纯文本 (.txt)'),
              onTap: () => _performExport('txt'),
            ),
            ListTile(
              leading: const Icon(Icons.code),
              title: const Text('JSON (.json)'),
              onTap: () => _performExport('json'),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
        ],
      ),
    );
  }

  /// 执行导出 - Perform Export
  Future<void> _performExport(String format) async {
    try {
      final prompt = state.prompt.value;
      if (prompt == null) return;

      Get.back(); // 关闭对话框

      final filePath = await StorageService.to.exportPrompt(prompt, format);
      
      if (filePath != null) {
        Get.snackbar(
          '导出成功',
          '文件已保存到: $filePath',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green[100],
          colorText: Colors.green[800],
          duration: const Duration(seconds: 3),
        );
      } else {
        Get.snackbar(
          '错误',
          '导出失败，请重试',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[800],
        );
      }
    } catch (e) {
      // print('导出失败 - Export failed: $e');
      Get.snackbar(
        '错误',
        '导出失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 查看版本历史 - View Version History
  void viewVersionHistory() {
    final prompt = state.prompt.value;
    if (prompt == null) return;

    Get.toNamed('/version', parameters: {'id': prompt.id});
  }

  /// 删除 Prompt - Delete Prompt
  void deletePrompt() {
    final prompt = state.prompt.value;
    if (prompt == null) return;

    Get.dialog(
      AlertDialog(
        title: const Text('确认删除'),
        content: Text('确定要删除 "${prompt.title}" 吗？\n\n此操作不可撤销，将同时删除所有版本历史。'),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('取消'),
          ),
          ElevatedButton(
            onPressed: () => _performDelete(prompt.id),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
            child: const Text('删除'),
          ),
        ],
      ),
    );
  }

  /// 执行删除 - Perform Delete
  Future<void> _performDelete(String promptId) async {
    try {
      Get.back(); // 关闭确认对话框

      final success = await StorageService.to.deletePrompt(promptId);
      
      if (success) {
        Get.back(); // 返回上一页
        Get.snackbar(
          '已删除',
          'Prompt 已删除成功',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.green[100],
          colorText: Colors.green[800],
          duration: const Duration(seconds: 2),
        );
      } else {
        Get.snackbar(
          '错误',
          '删除失败，请重试',
          snackPosition: SnackPosition.TOP,
          backgroundColor: Colors.red[100],
          colorText: Colors.red[800],
        );
      }
    } catch (e) {
      // print('删除失败 - Delete failed: $e');
      Get.snackbar(
        '错误',
        '删除失败，请重试',
        snackPosition: SnackPosition.TOP,
        backgroundColor: Colors.red[100],
        colorText: Colors.red[800],
      );
    }
  }

  /// 刷新数据 - Refresh Data
  Future<void> refreshData() async {
    final prompt = state.prompt.value;
    if (prompt != null) {
      await loadPromptDetail(prompt.id);
    }
  }

  /// 显示详细统计 - Show Detailed Statistics
  void showDetailedStatistics() {
    final prompt = state.prompt.value;
    if (prompt == null) return;

    final stats = prompt.getStatistics();
    
    Get.dialog(
      AlertDialog(
        title: const Text('详细统计'),
        content: SizedBox(
          width: double.maxFinite,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: stats.entries.map((entry) {
                return Padding(
                  padding: const EdgeInsets.symmetric(vertical: 4),
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        entry.key,
                        style: const TextStyle(fontWeight: FontWeight.w500),
                      ),
                      Text(
                        entry.value.toString(),
                        style: TextStyle(color: Colors.grey[600]),
                      ),
                    ],
                  ),
                );
              }).toList(),
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }

  /// 显示变量详情 - Show Variable Details
  void showVariableDetails() {
    final prompt = state.prompt.value;
    if (prompt == null || !prompt.getHasTemplateVariables()) return;

    Get.dialog(
      AlertDialog(
        title: const Text('模板变量详情'),
        content: SizedBox(
          width: double.maxFinite,
          child: SingleChildScrollView(
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              mainAxisSize: MainAxisSize.min,
              children: prompt.templateVariables.map((variable) {
                return Card(
                  margin: const EdgeInsets.only(bottom: 8),
                  child: Padding(
                    padding: const EdgeInsets.all(12),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(
                          '{{${variable.name}}}',
                          style: const TextStyle(
                            fontFamily: 'monospace',
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                        if (variable.description.isNotEmpty) ...[
                          const SizedBox(height: 4),
                          Text(variable.description),
                        ],
                        const SizedBox(height: 8),
                        Wrap(
                          spacing: 8,
                          children: [
                            Chip(
                              label: Text(variable.type),
                              backgroundColor: Colors.blue[100],
                            ),
                            if (variable.isRequired)
                              Chip(
                                label: const Text('必需'),
                                backgroundColor: Colors.red[100],
                              ),
                            if (variable.defaultValue.isNotEmpty)
                              Chip(
                                label: Text('默认: ${variable.defaultValue}'),
                                backgroundColor: Colors.green[100],
                              ),
                          ],
                        ),
                      ],
                    ),
                  ),
                );
              }).toList(),
            ),
          ),
        ),
        actions: [
          TextButton(
            onPressed: () => Get.back(),
            child: const Text('关闭'),
          ),
        ],
      ),
    );
  }
}